import type { VersionWithStats } from '@/api/version'
import { ResponseParser } from '@/utils/responseParser'

/**
 * 提取版本列表响应中的版本数组，兼容多种后端返回结构。
 */
export const extractVersionItems = (payload: unknown): VersionWithStats[] => {
  try {
    const parsed = ResponseParser.parseListResponse<VersionWithStats>(payload as any)
    if (parsed.items?.length) {
      return normalizeVersionList(parsed.items)
    }
  } catch {
    // ignore and fall back to manual extraction
  }

  const visited = new Set<unknown>()
  const queue: unknown[] = [payload]

  while (queue.length > 0) {
    const current = queue.shift()
    if (!current || visited.has(current)) {
      continue
    }
    visited.add(current)

    if (Array.isArray(current)) {
      return normalizeVersionList(current)
    }

    if (typeof current === 'object') {
      const maybeItems = (current as Record<string, unknown>).items
      if (Array.isArray(maybeItems)) {
        return normalizeVersionList(maybeItems)
      }

      const maybeData = (current as Record<string, unknown>).data
      if (maybeData !== undefined) {
        queue.push(maybeData)
      }

      const maybeResult = (current as Record<string, unknown>).result
      if (maybeResult !== undefined) {
        queue.push(maybeResult)
      }
    }
  }

  return []
}

const normalizeVersionList = (list: unknown[]): VersionWithStats[] => {
  const seen = new Set<string>()

  return list
    .map((item) => normalizeVersion(item))
    .filter((item): item is VersionWithStats => {
      if (!item) return false
      if (seen.has(item.id)) return false
      seen.add(item.id)
      return true
    })
}

const normalizeVersion = (item: unknown): VersionWithStats | null => {
  if (!item || typeof item !== 'object') {
    return null
  }

  const record = item as Record<string, unknown>
  const rawId = record.id ?? record._id
  if (!rawId) {
    return null
  }

  const normalized: Record<string, unknown> = {
    ...record,
    id: String(rawId)
  }

  if (normalized.project_id !== undefined) {
    normalized.project_id = String(normalized.project_id)
  }

  return normalized as VersionWithStats
}

